package cn.sylinx.hbatis.ext.function.impl;

import cn.sylinx.hbatis.exception.FunctionException;
import cn.sylinx.hbatis.ext.function.IFunction;
import cn.sylinx.hbatis.ext.parse.ValueTokenHandler;

/**
 * <pre>
 * 自定义 like函数，使用方法： 
 * #FUNC[like, email, emailLikeStr] 任意匹配
 * #FUNC[like, email, emailLikeStr,1]  右边字符全匹配
 * #FUNC[like, email, emailLikeStr,2]  左边字符全匹配
 * </pre>
 * 
 * @author johnhan
 *
 */
public class Like implements IFunction {

	public String sqlAlias() {
		return "like";
	}

	public String invoke(ValueTokenHandler valueTokenHandler, String inputStr) {

		String[] kv = inputStr.split(",");
		int len = kv.length;

		if (kv == null || len < 2) {
			throw new FunctionException(sqlAlias() + "函数的入参错误");
		}

		byte lt = 0; // 表示全匹配
		if (len > 2) {
			String extra = kv[2].trim();
			try {
				lt = Byte.valueOf(extra);
			} catch (Exception e) {
			}
		}

		String field = kv[0].trim();
		String params = kv[1].trim();

		Object value = valueTokenHandler.hand(params);
		if (value == null) {
			return "";
		}

		String likeStrPre = field + " like ";
		String likeStrPost = "'%" + value + "%'";
		if (lt == 0) {
			// 全匹配
			likeStrPost = "'%" + value + "%'";
		} else if (lt == 1) {
			// 右边全匹配
			likeStrPost = "'%" + value + "'";
		} else if (lt == 2) {
			// 左边全匹配
			likeStrPost = "'" + value + "%'";
		}

		return likeStrPre + likeStrPost;
	}

}
